package mysql

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"pharymacy-management-system/models"
)

const (
	secret               = "wuzhuya.top"
	ErrorUserExist       = "用户已存在"
	ErrorUserNotExist    = "用户不存在"
	ErrorInvalidPassword = "用户名或密码错误"
)

func CheckUserExist(username string) (err error) {
	sqlStr := `select count(user_id) from w_user where username=? and is_delete=1`
	var count int
	if err = db.Get(&count, sqlStr, username); err != nil {
		return
	}
	if count > 0 {
		err = errors.New(ErrorUserExist)
	}
	return
}

func InsertUser(user *models.User) (err error) {
	// 对密码进行加密
	user.Password = encryptPassword(user.Password)
	// 默认新用户权限为2，即普通用户
	userAuthority := models.UserAuthority{
		UserID:      user.UserID,
		AuthorityID: 2,
	}
	// 开启事务
	tx, err := db.Beginx()
	if err != nil {
		return
	}
	// 执行SQL语句入库
	sqlStr := `insert into w_user(user_id,username,password) value (?,?,?)`
	sqlStr2 := `insert into w_user_authority(user_id, authority_id) value (?,?)`
	tx.MustExec(sqlStr, user.UserID, user.Username, user.Password)
	tx.MustExec(sqlStr2, userAuthority.UserID, userAuthority.AuthorityID)
	// 提交事务
	err = tx.Commit()
	return
}

func Login(user *models.User) (err error) {
	sqlStr := `select user_id,username,password from w_user where username=? and password=? and is_delete=1`
	err = db.Get(user, sqlStr, user.Username, encryptPassword(user.Password))
	if err != nil {
		return
	}
	if user == nil {
		return errors.New(ErrorInvalidPassword)
	}
	return
}

func SelectUserByUserID(userID int64) (*models.User, error) {
	var user models.User
	sqlStr := `select user_id,username,password,user_nick_name, create_time,update_time,is_delete from w_user where user_id=? and is_delete=1`
	err := db.Get(&user, sqlStr, userID)
	if err != nil {
		return nil, err
	}
	var authority models.Authority
	sqlStr = `select authority_id,authority_name from w_authority where authority_id=(select authority_id from w_user_authority where user_id=?)`
	err = db.Get(&authority, sqlStr, user.UserID)
	if err != nil {
		return nil, err
	}
	user.Authority = &authority
	return &user, err
}

func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}

func UpdateUserNickNameByUserID(user *models.User) (err error) {
	sqlStr := `update w_user set user_nick_name=? where user_id=?`
	_, err = db.Exec(sqlStr, user.UserNickName, user.UserID)
	if err != nil {
		return
	}
	return nil
}

func SelectAllUser() (userList []models.User, err error) {
	//sqlStr := `select * from w_user where is_delete=1`
	sqlStr := `select user_id,username,user_nick_name, create_time,update_time,is_delete from w_user where is_delete=1`
	err = db.Select(&userList, sqlStr)
	return
}

func DeleteUserByUserID(userID int64) error {
	sqlStr := `update w_user set is_delete=0 where user_id=?`
	_, err := db.Exec(sqlStr, userID)
	return err
}
